import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { LoginRequest, LoginResponse, UserInfo } from '@/types/auth'
import { authApi } from '@/api/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>(localStorage.getItem('token') || '')
  const refreshToken = ref<string>(localStorage.getItem('refreshToken') || '')
  const userInfo = ref<UserInfo | null>(null)
  const permissions = ref<string[]>([])

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)

  // 登录
  const login = async (credentials: LoginRequest): Promise<boolean> => {
    try {
      const response = await authApi.login(credentials)

      token.value = response.token
      refreshToken.value = response.refreshToken

      // 保存到本地存储
      localStorage.setItem('token', response.token)
      localStorage.setItem('refreshToken', response.refreshToken)

      // 获取用户信息
      await getUserInfo()

      ElMessage.success('登录成功')

      // 跳转到首页或重定向页面
      const redirect = router.currentRoute.value.query.redirect as string
      router.push(redirect || { name: 'Dashboard' })

      return true
    } catch (error: any) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  // 登出
  const logout = async (): Promise<void> => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      refreshToken.value = ''
      userInfo.value = null
      permissions.value = []

      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')

      ElMessage.success('已登出')
      router.push({ name: 'Login' })
    }
  }

  // 获取用户信息
  const getUserInfo = async (): Promise<void> => {
    try {
      const user = await authApi.getUserInfo()
      userInfo.value = user

      // 获取用户权限
      const permissionList = await authApi.getUserPermissions()
      permissions.value = permissionList
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 刷新Token
  const refreshAccessToken = async (): Promise<boolean> => {
    try {
      const response = await authApi.refreshToken(refreshToken.value)

      token.value = response.token
      refreshToken.value = response.refreshToken

      localStorage.setItem('token', response.token)
      localStorage.setItem('refreshToken', response.refreshToken)

      return true
    } catch (error) {
      console.error('刷新Token失败:', error)
      // 刷新失败，清除状态并跳转到登录页
      await logout()
      return false
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = (role: string): boolean => {
    return userInfo.value?.roles.includes(role) || false
  }

  // 更新用户信息
  const updateUserInfo = (info: Partial<UserInfo>): void => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info }
    }
  }

  return {
    // 状态
    token,
    refreshToken,
    userInfo,
    permissions,

    // 计算属性
    isAuthenticated,

    // 方法
    login,
    logout,
    getUserInfo,
    refreshAccessToken,
    hasPermission,
    hasRole,
    updateUserInfo
  }
})